<?php
class Administrator_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
	
	/*Check Login*/
	function check_login()
	{
		if(!@$this->session->userdata('adminData') && !($this->router->method == "login" || $this->router->method == "forget")):
			/*Redirect*/
			redirect($this->data['admin_path'].'login');
		elseif($this->session->userdata('adminData') && ($this->router->method == "login" || $this->router->method == "forget")):
			/*Redirect*/
			redirect($this->data['admin_path']);			
		endif;		
	}
	
	/*Login*/
	function login()
	{
		$user_login = $this->input->post('user_login');
		$user_pass = $this->input->post('user_pass');
		if(!empty($user_login)):
			$is_exist = $this->db->from('user')
			->where("(username = '".$user_login."' OR email = '".$user_login."') AND password = '".$user_pass."'")
			->count_all_results();
			if(!empty($is_exist)):
				/*Get User*/	
				$dataUser = $this->db->get_where('user',"(username = '".$user_login."' OR email = '".$user_login."') AND password = '".$user_pass."'",1)->row();
							
				/*Get Permission*/
				$dataPermission = $this->db->join('mainmenu as j','j.mainmenu_id=user_group_permission.mainmenu_id','left')->join('submenu as k','k.submenu_id=user_group_permission.submenu_id','left')->order_by('j.mainsort_id,k.subsort_id','ASC')->get_where('user_group_permission',array('user_group_permission.group_id' => $dataUser->group_id))->result();
				
				/*Update Last Login*/
				$this->db->set('last_login', 'NOW()', FALSE);  
				$this->db->set('last_ip_address', ''.$this->input->ip_address().''); 
				$this->db->where('user_id',$dataUser->user_id);
				$this->db->update('user');
				
				/*High Algolythm*/
				$generate_menu = array();
				$array_id = array();	
				foreach($dataPermission as $key => $value):
					if(!in_array($value->mainmenu_id,$array_id)):
						$generate_menu[$value->mainmenu_id] = array(
							'mainmenu_id' => $value->mainmenu_id,
							'main_name' => $value->main_name,
							'main_icon' => $value->main_icon,
							'main_page' => $value->main_page
						);
						//Add Menu in array
						$array_id[] = $value->mainmenu_id;				
					endif;
					$generate_menu[$value->mainmenu_id]['submenu'][] = array(
						'submenu_id' => $value->submenu_id,
						'sub_name' => $value->sub_name,
						'sub_page' => $value->sub_page					
					);		
				endforeach;

		     	$userdata = array(
		    		'adminData' => array(
		    			'user_id' => $dataUser->user_id,
		    			'group_id' => $dataUser->group_id,
		    			'username' => $dataUser->username,
		    			'generate_menu' => $generate_menu,
		    		)
		    	);
		    	$this->session->set_userdata($userdata);  
		    	/*Redirect*/  	
				redirect(base_url($this->data['admin_path']));					
			else:
				$this->session->set_flashdata('error_message', 'Invalid username. <a href="'.base_url($this->data['admin_path'].'forget').'">Lost your password?</a>.');
			endif;
		else:
			$this->session->set_flashdata('error_message', 'Enter a username.');
		endif;
		/*Redirect*/
		redirect($this->data['admin_path']."login");		
	}
	/*Forget*/
	function forget()
	{
		$user_login = $this->input->post('user_login');
		if(!empty($user_login)):
			$is_exist = $this->db->from('user')
			->where("username = '".$user_login."' OR email = '".$user_login."'")
			->count_all_results();
			if(!empty($is_exist)):
				$dataResult = $this->db->select('username,password,email')
				->get_where('user',"username = '".$user_login."' OR email = '".$user_login."'",1)
				->row();
				/*Send E-Mail*/
				$this->load->library("email");
				$this->email->from("admin@oniphp.com", "ONIPHP CO.,LTD");
				$this->email->to($user_login);
				$this->email->subject("[".$this->data['admin_company']."] Recover your password");
				$this->email->message("Your password is following below:\nUsername: ".$dataResult->username."\nPassword: ".$dataResult->password."\n");
				$this->email->send();
				/*Redirect*/
				redirect(base_url($this->data['admin_path']));
			else:
				$this->session->set_flashdata('error_message', 'Username or E-mail is not valid.');
			endif;
		else:
			$this->session->set_flashdata('error_message', 'Enter a username or e-mail address.');
		endif;
		/*Redirect*/
		redirect($this->data['admin_path']."forget");	
	}
	
	function logout()
	{
		/*Delete Session*/
		$this->session->unset_userdata('adminData');
		@delete_cookie('rememberme');
		/*Redirect*/
		redirect($this->data['admin_path']);	
	}	
	
	private function rememberme()
	{
		$mycookie = array(
			'name'  => 'rememberme',
			'value' => $this->session->userdata('adminData')['user_id'],
			'expire'=> '86500'
		);
		set_cookie($mycookie);		
	}
	
	public function generate_menu()
	{
		$main_page = preg_replace('/'.trim($this->data['admin_path'],'/').'_/','',$this->router->class);			
		$sub_page = $this->router->method;	
		$main_total = count($this->session->userdata('adminData')['generate_menu']);	
		$html = "<ul id=\"adminmenu\" role=\"navigation\">";
		foreach($this->session->userdata('adminData')['generate_menu'] as $key => $value):
			$classes = $value['main_icon']." wp-has-submenu menu-top ";
			/*Check First Menu*/
			if($key == 1) $classes .= "wp-first-item menu-top-first ";
			/*Check Last Menu*/
			if($key == intval($main_total)) $classes .= "menu-top-last ";
			/*Check Main Page*/
			if($value['main_page'] == $main_page):
				$classes .= "wp-has-current-submenu wp-menu-open";
			else:
				$classes .= "wp-not-current-submenu";
			endif;
			
			$html .= "<li class=\"".$classes."\" id=\"".$value['main_icon']."\">\n";	
			$html .= "<a href=\"".base_url($this->data['admin_path'].$value['main_page'].'/'.$value['submenu'][0]['sub_page'])."\" class=\"".$classes."\" aria-haspopup=\"true\">\n";	
			$html .= "<div class=\"wp-menu-arrow\"><div></div></div><div class=\"wp-menu-image\"><br /></div>\n";	
			$html .= "<div class=\"wp-menu-name\">".$value['main_name']."</div>\n";	
			$html .= "</a>\n";	
			$html .= "<ul class=\"wp-submenu wp-submenu-wrap\">\n";	
			$html .= "<li class=\"wp-submenu-head\">".$value['main_name']."</li>\n";
			foreach($value['submenu'] as $keySub => $valueSub):
				$classesSub = "";
				/*Check First Menu*/
				if($keySub == 0) $classesSub .= "wp-first-item ";
				/*Check Sub Page*/
				if($valueSub['sub_page'] == $sub_page) $classesSub .= "current";
				$html .= "<li class=\"".$classesSub."\">\n";	
				$html .= "<a href=\"".base_url($this->data['admin_path'].$value['main_page'].'/'.$valueSub['sub_page'])."\" class=\"".$classesSub."\">".$valueSub['sub_name']."</a>\n";	
				$html .= "</li>\n";
			endforeach;	
			$html .= "</ul>\n";	
			$html .= "</li>\n";	
		endforeach;
		$html .="<li id=\"collapse-menu\" class=\"hide-if-no-js\"><div id=\"collapse-button\"><div></div></div><span>Collapse menu</span></li>";
		$html .= "</ul>";
		return $html;
	}	
}

?>